﻿using JESAI.Caching;
using Microsoft.AspNetCore.Mvc.Filters;

namespace JESAI.Framework.Idempotents
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class IdempotentKeyAttribute : Attribute, IFilterFactory
    {
        /// <summary>
        /// IdempotentKeyAttributeFilterType类型
        /// 1. Key: 基于请求参数的唯一标识
        /// 2. Params：基于请求参数的唯一标识，并将请求参数值作为缓存值
        /// </summary>
        public IdempotentKeyAttributeFilterType FilterType { get; set; } = IdempotentKeyAttributeFilterType.Key;

        /// <summary>
        /// 缓存时间，单位：毫秒
        /// </summary>
        private double CacheMillisecond { get; set; } = 10 * 60 * 1000;
        public bool IsReusable => false;

        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
        {
            var distributedCache = (CacheManager)serviceProvider.GetService(typeof(CacheManager));
            return new IdempotentKeyAttributeFilter(distributedCache, FilterType, CacheMillisecond);
        }
    }
}
